package com.example.shop.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import com.alibaba.fastjson.JSON;
import com.example.shop.controller.UserController;
import com.example.shop.pojo.User;
import com.example.shop.utils.BaseContext;
import com.example.shop.utils.Result;
import com.example.shop.utils.UserIdSession;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录拦截器
 */
//@WebFilter(value = "/*" )
public class LoginFilter implements Filter {
	// 日志对象
	private final static Logger log = LoggerFactory.getLogger(UserController.class);

	// 路径匹配器：支持通配符
	private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		// 获取本次请求的uri判断是否放行
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		log.info("拦截到请求: {}", request.getRequestURI());
		// 设置放行的资源
		String[] uris = new String[] {"/user/register","/user/login","/user/logout","/user/sendMsg/"
				 };
		for (String uri : uris) {
			// 如果本次请求的URI和uri一样则放行
			if (PATH_MATCHER.match(uri, request.getRequestURI())) {
				filterChain.doFilter(request, response);
				log.info("放行请求： {}", request.getRequestURI());
				return;
			}
		}
		// （1）判断员工是否已经登录，如果没有登录则跳回登录界面
		 String userJsonString = extractJsonData(request); 
		 User user = (User)JSON.parseObject( userJsonString,User.class);
		 
		 Object employee = UserIdSession.getAttribute(user.getAccount());
		//Object employee = UserIdSession.getAttribute("10086");
		
		if (employee != null) {
			System.out.println("已登录");
			// 已经登录
			BaseContext.setAccountId(user.getAccount());
			System.out.println("*****");
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}else {
			// 还没登录，跳回登录页面
			System.out.println("未登录");
			response.getWriter().write(JSON.toJSONString(Result.fail("NOTLOGIN")));
		}
	}
	 private String extractJsonData(HttpServletRequest request) throws IOException {
	        // 从请求体中读取 JSON 数据
	        StringBuilder requestBody = new StringBuilder();
	      
	        BufferedReader reader = request.getReader();
	        String line;
	        while ((line = reader.readLine()) != null) {
	        	
	        	
	            requestBody.append(line);
	        }
	       
	        reader.close();

	        return requestBody.toString();
	    }
	 
}